<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CarController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct ()
    {
        //
    }

    /**
     * 获取汽车三级联动车系接口
     * return 
     * status: 0 成功 1 失败
     * firstLevel: 第一级汽车品牌
     * secondLevel: 第二级汽车小品牌
     * thirdLevel: 第三级汽车车系
     *
     * @return void
     */
    public function carLevel ()
    {
        $levelData = DB::table('carLevel')->get();
        $levelData = json_decode(json_encode($levelData), true);

        $firstLevel = array();
        $secondLevel = array();
        $thirdLevel = array();
        foreach ($levelData as $key => $value) {
            if (!in_array($value['firstlevel'], $firstLevel)) {
                $firstLevel[] =  $value['firstlevel'];
            }

            if (!empty($secondLevel[$value['firstlevel']])) {
                if (!in_array($value['secondlevel'], $secondLevel[$value['firstlevel']])) {
                    $secondLevel[$value['firstlevel']][] = $value['secondlevel'];
                }
            } else {
                $secondLevel[$value['firstlevel']][] = $value['secondlevel'];
            }
            
            if (!empty($thirdLevel[$value['secondlevel']])) {
                if (!in_array($value['thirdlevel'], $thirdLevel[$value['secondlevel']])) {
                    $thirdLevel[$value['secondlevel']][] = $value['thirdlevel'];
                }
            } else {
                $thirdLevel[$value['secondlevel']][] = $value['thirdlevel'];
            }
        }

        return ['status' => 0, 'firstlevel' => $firstLevel, 'secondlevel' => $secondLevel, 'thirdlevel' => $thirdLevel];
    }

    /**
     * 获取汽车具体车系下包含车型接口
     * $level string 需要获取的具体第三级的车系名
     * return 
     * status: 0 成功 1 失败
     * data: 具体车系下的所有车型数据数组
     *
     * @return void
     */
    public function carModel (Request $request)
    {
        $messages = [
            'required' => ':attribute 的字段必填'
        ];

        $this->validate($request, [
            'level' => 'required',
        ], $messages);

        $modelData = DB::table('carModel')->where('carName', $request['level'])->get();
        $modelData = json_decode(json_encode($modelData), true);

        return ['status' => 0, 'data' => $modelData];
    }
}
